#!/bin/bash
#
# Copyright 2020 The Magma Authors.

# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script generates certs for the proxy tier for dev and testing
set -e

if [ "$TEST_MODE" != "1" ]; then
  echo "Not running in test mode!"
  exit 0
fi

DIR='/var/opt/magma/certs'
mkdir -p ${DIR}
cd ${DIR}

if [ ! -f rootCA.pem ]; then
  echo "##################"
  echo "Creating root CA.."
  echo "##################"
  openssl genrsa -out rootCA.key 2048
  openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 365000 \
        -out rootCA.pem -subj "/C=US/CN=rootca.magma.test"
fi

if [ ! -f controller.crt ]; then
  echo "##########################"
  echo "Creating controller cert.."
  echo "##########################"
  openssl genrsa -out controller.key 2048
  openssl req -new -key controller.key -out controller.csr \
        -subj "/C=US/CN=*.magma.test"
  openssl x509 -req -in controller.csr -CA rootCA.pem -CAkey rootCA.key \
        -CAcreateserial -out controller.crt -days 36400 -sha256
fi

if [ ! -f certifier.key ]; then
  echo "#######################"
  echo "Creating certifier CA.."
  echo "#######################"
  openssl genrsa -out certifier.key 2048
  openssl req -x509 -new -nodes -key certifier.key -sha256 -days 365000 \
        -out certifier.pem -subj "/C=US/CN=certifier.magma.test"
fi
